package com.ofsoft.weixin.mp;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ofsoft.weixin.core.SignUtil;
import com.ofsoft.weixin.core.utils.StringUtil;
import com.ofsoft.weixin.mp.message.MessageController;
import com.ofsoft.weixin.mp.message.MessageHandlerBase;

/**
 * 微信服务端验证
 * 
 * @author OF
 * @date 2017年10月10日
 */
public class Dispatcher {
	private static final Logger log = LoggerFactory.getLogger(Dispatcher.class);

	/**
	 * <pre>
	 * get 请求验证消息
	 * </pre>
	 */
	public static void doCheck(HttpServletRequest request,
			HttpServletResponse response) {
		OutputStream ops = null;
		try {
			// 加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 字符
			String echostr = request.getParameter("echostr");
			log.debug("WeChat signature:" + signature + ",timestamp:"
					+ timestamp + ",nonce:" + nonce + ",echostr:" + echostr);
			// 签名判断
			if (SignUtil.getSignature(signature, AppConfig.getAppToken(),
					timestamp, nonce)) {
				ops = response.getOutputStream();
				ops.write(echostr.getBytes());
				ops.flush();
				ops.close();
				log.debug("接入成功！！！");
			} else {
				log.error("接入失败token验证失败！！！！！！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("签名失败！！！！！！");
		} finally {
			if (null != ops) {
				try {
					ops.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 数据处理入口
	 * 
	 * @param request
	 * @param response
	 */
	public static void doDispatch(HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtil.isNotBlank(request.getParameter("echostr"))) {
			doCheck(request, response);
		} else {
			doService(request, response, null);
		}
	}

	/**
	 * 数据处理入口
	 * 
	 * @param request
	 * @param response
	 */
	public static void doDispatch(HttpServletRequest request,
			HttpServletResponse response, MessageController messageController) {
		if (StringUtil.isNotBlank(request.getParameter("echostr"))) {
			doCheck(request, response);
		} else {
			doService(request, response, messageController);
		}
	}

	public static void doService(HttpServletRequest request,
			HttpServletResponse response, MessageController messageController) {
		log.debug("============================处理微信消息开始===============================");
		try {
			// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			// 调用核心业务类接收消息、处理消息
			MessageHandlerBase handlerBase = HandlerFactory.getMessageHandler();
			String result = handlerBase.handler(request, messageController);
			OutputStream out = response.getOutputStream();
			if (result == null) {
				result = "";
			}
			out.write(result.getBytes("utf-8"));
			out.close();
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.debug("============================处理微信消息结束===============================");
	}

}
